﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using MinhTam.DataAccess.Web;
using MinhTam.Objects;
using System.IO;

public partial class OptionSlideShow: System.Web.UI.Page
{
 
    protected void Page_Load(object sender, EventArgs e)
    {
       // Page.Form.Attributes.Add("enctype", "multipart/form-data");
        if (!IsPostBack)
        {

            InitSlideShow();
        }
      
    } 
    #region Slide show
    private void InitSlideShow()
    {
  
        InitCtrlSlide();
        InitDataSlide();
    }
    private void InitCtrlSlide()
    {
        HelpControls.InitListLoaiBaiViet(ddLoaiBVSlide);
    }
    private void InitDataSlide()
    {
        string sql = string.Format(@"SELECT ROW_NUMBER() OVER (ORDER BY isnull(ha.SAP_XEP,9999),ha.ngay_tao) STT, ha.ID,'{0}'+ ha.URL_IMAGE URL_IMAGE,ha.BAI_VIET_ID,
                        ha.SAP_XEP,ha.URL_LINK,bv.LOAI_BAI_VIET, ha.NGAY_TAO, bv.TEN_BAI_VIET, isnull(ha.is_hiden,'N') is_hiden, case when isnull(ha.is_hiden,'N')='N' then 0 else 1 end IS_HIDEN_B
                        FROM HINH_ANH ha
                        LEFT JOIN BAI_VIET bv ON bv.BAI_VIET_ID=ha.BAI_VIET_ID 
                        where ha.album_id='{1}'", HelpConstEnum.ADMIN_UPLOAD_IMAGE_FOLDER,
                        HelpConstEnum.LoaiAlbum.SLIDE_SHOW.GetHashCode());
        DataTable dt=SQLConnectWeb.GetTable(sql);
        gridViewSlideShow.DataKeyNames = new string[]
        {
            HINH_ANH.cl_ID,
            HINH_ANH.cl_BAI_VIET_ID,
            BAI_VIET.cl_LOAI_BAI_VIET,         
            HINH_ANH.cl_NGAY_TAO,
            HINH_ANH.cl_URL_LINK,
            HINH_ANH.cl_SAP_XEP,
            HINH_ANH.cl_IS_HIDEN,
            HINH_ANH.cl_URL_IMAGE
        
        };
      
        gridViewSlideShow.DataSource = dt;
        gridViewSlideShow.DataBind();
       
    }
    protected void ddLoaiBVSlide_SelectedIndexChanged(object sender, EventArgs e)
    {
       
        string sql = string.Format(@"SELECT BV.BAI_VIET_ID,BV.TEN_BAI_VIET + ' ('+CONVERT(VARCHAR(10),BV.NGAY_TAO,103)+')' TEN_BAI_VIET, bv.HINH_THUMBNAIL
        FROM BAI_VIET BV WHERE BV.DUYET='Y' AND BV.LOAI_BAI_VIET = {0} ORDER BY BV.NGAY_TAO
        ", ddLoaiBVSlide.SelectedValue);
        DataTable dt = SQLConnectWeb.GetTable(sql);
        HelpControls.InitDropDownList(ddlBVSlide, dt, "BAI_VIET_ID", "TEN_BAI_VIET");
 

    }
    protected void ddlBVSlide_SelectedIndexChanged(object sender, EventArgs e)
    {
        string id = HelpControls.GetValueDDL(ddlBVSlide);
  
        {
           
            txtURLSlide.Text = ("~/bvchitiet.aspx?id=" + id);
        }

    }
    protected void btnSaveSlideShow_Click(object sender, EventArgs e)
    {
        string imgPath = "";
        if (string.IsNullOrEmpty(keySlide.Value))
        {

            if ((!uploadSlide.HasFile || uploadSlide.PostedFile.ContentLength == 0) && imageSlide.ImageUrl == "")
            {
                HelpControls.ShowMsgBox(this, "Vui lòng chọn hình ảnh!");
                this.uploadSlide.Focus();
                return;
            }
            imgPath = Path.GetFileName(imageSlide.ImageUrl);
            if (uploadSlide.FileName != "")
            {

                string ext = System.IO.Path.GetExtension(uploadSlide.FileName);
                imgPath = "IMG_" + DateTime.Now.ToString(HelpConstEnum.ADMIN_FILE_DATEFORMAT) + ext;
                string path = Server.MapPath(HelpConstEnum.ADMIN_UPLOAD_IMAGE_FOLDER + "TEMP_"+imgPath);
                uploadSlide.SaveAs(path);
                System.Drawing.Image img = System.Drawing.Image.FromFile(path);
                System.Drawing.Image newImg = HelpUtil.ReSizeImage(img, HelpConstEnum.SLIDE_IMG_WITH, HelpConstEnum.SLIDE_IMG_HEIGH);
                newImg.Save(Server.MapPath(HelpConstEnum.ADMIN_UPLOAD_IMAGE_FOLDER + imgPath));
                try{
                    img.Dispose();
                    File.Delete(path);
                }catch{
                }
            }
            string sqlI = @"INSERT INTO HINH_ANH (URL_IMAGE,NGUOI_TAO,NGAY_TAO,ALBUM_ID,URL_LINK,BAI_VIET_ID,SAP_XEP)
                        VALUES (@URL_IMAGE,	@NGUOI_TAO,	getdate(),@ALBUM_ID,@URL_LINK,	@BAI_VIET_ID,@SAP_XEP)";
            bool ok = SQLConnectWeb.ExecuteNonQuery(sqlI,
                new object[]{
                    "@URL_IMAGE",imgPath,
                    "@NGUOI_TAO",UserLogin.USER_ID(this),
                    "@ALBUM_ID",HelpConstEnum.LoaiAlbum.SLIDE_SHOW.GetHashCode(),
                    "@URL_LINK",txtURLSlide.Text.Trim(),
                     "@BAI_VIET_ID",HelpControls.GetValueDDL(ddlBVSlide),
                     "@SAP_XEP",HelpUtil.ParseDecimal(txtSapXepSlide.Text)

                }) > 0;
            if (ok)
            {
                imageSlide.ImageUrl = HelpConstEnum.ADMIN_UPLOAD_IMAGE_FOLDER + imgPath;
                sqlI = string.Format(@"select top 1 id from hinh_anh where album_id ={0} order by id desc", HelpConstEnum.LoaiAlbum.SLIDE_SHOW.GetHashCode());
                DataTable dt = SQLConnectWeb.GetTable(sqlI);
                if (dt != null && dt.Rows.Count > 0)
                {
                    keySlide.Value = dt.Rows[0]["id"].ToString();
                    lblNgayTaoSlide.Text = DateTime.Now.ToString("dd/MM/yyyy HH:mm");
                }
                InitDataSlide();
            }

        }
        else
        {
            imgPath = Path.GetFileName(imageSlide.ImageUrl);
         
            if (uploadSlide.FileName != "")
            {
              
                string ext = System.IO.Path.GetExtension(uploadSlide.FileName);
                imgPath = "IMG_" + DateTime.Now.ToString(HelpConstEnum.ADMIN_FILE_DATEFORMAT) + ext;
                string path = Server.MapPath(HelpConstEnum.ADMIN_UPLOAD_IMAGE_FOLDER + "TEMP_" + imgPath);
                uploadSlide.SaveAs(path);
                System.Drawing.Image img = System.Drawing.Image.FromFile(path);
                System.Drawing.Image newImg = HelpUtil.ReSizeImage(img, HelpConstEnum.SLIDE_IMG_WITH, HelpConstEnum.SLIDE_IMG_HEIGH);
                newImg.Save(Server.MapPath(HelpConstEnum.ADMIN_UPLOAD_IMAGE_FOLDER + imgPath));
                try
                {
                    img.Dispose();
                 
                    File.Delete(path);
                    
                }
                catch
                {
                }
          
               


            }
            string sqlU = @"UPDATE HINH_ANH
                         SET	
	                    URL_IMAGE = @URL_IMAGE,	
	                    URL_LINK = @URL_LINK,	
	                    BAI_VIET_ID = @BAI_VIET_ID,
	                    SAP_XEP = @SAP_XEP,
	                    IS_HIDEN = @IS_HIDEN where ID=@ID";
            bool ok = SQLConnectWeb.ExecuteNonQuery(sqlU,
                new object[]{
                    "@URL_IMAGE",imgPath,
                    "@URL_LINK",txtURLSlide.Text.Trim(),
                    "@BAI_VIET_ID",HelpControls.GetValueDDL(ddlBVSlide),
                    "@SAP_XEP",HelpUtil.ParseDecimal(txtSapXepSlide.Text),
                    "@IS_HIDEN",ckcHiden.Checked?"Y":"N",
                    "@ID",keySlide.Value
                }) > 0;
            if (ok)
            {
                if(imgPath!=System.IO.Path.GetFileName(imageSlide.ImageUrl))
                    HelpUtil.DeleteFile(this, imageSlide.ImageUrl); ;
                imageSlide.ImageUrl = HelpConstEnum.ADMIN_UPLOAD_IMAGE_FOLDER + imgPath;
                InitDataSlide();

            }
            else
            {
                HelpControls.ShowMsgBox(this, "Cập nhật dữ liệu không thành công!");
            }
        }
    }
    protected void gridViewSlideShow_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandArgument == null || e.CommandArgument == "") return;
        int index=int.Parse(e.CommandArgument.ToString());
        DataKey row = gridViewSlideShow.DataKeys[index];
        if (e.CommandName == "cmdEdit")
        {
            //   GridViewRow row = gridViewData.Rows[];

            keySlide.Value = row.Values[HINH_ANH.cl_ID].ToString();
            HelpControls.SetValueDDL(ddLoaiBVSlide, row.Values[BAI_VIET.cl_LOAI_BAI_VIET].ToString());
    
            ddLoaiBVSlide_SelectedIndexChanged(null, null);
            HelpControls.SetValueDDL(ddlBVSlide, row.Values[HINH_ANH.cl_BAI_VIET_ID].ToString());
            txtURLSlide.Text = row.Values[HINH_ANH.cl_URL_LINK].ToString();
            txtSapXepSlide.Text = row.Values[HINH_ANH.cl_SAP_XEP].ToString();
            ckcHiden.Checked = row.Values[HINH_ANH.cl_IS_HIDEN].ToString() == "Y";
            imageSlide.ImageUrl =  row.Values["URL_IMAGE"].ToString();
            btnSaveSlideShow.Text = "Cập nhật";

        }
        else if (e.CommandName == "cmdDelete")
        {
            string delete = row.Values[HINH_ANH.cl_ID].ToString();
            // HelpControls.ShowMsgBoxConfirmDelete(this);
            string sql = string.Format("delete from {0} where {1}={2}", HINH_ANH.sTableName, HINH_ANH.cl_ID, delete);
            if (SQLConnectWeb.ExecSQL(sql))
            {
                HelpUtil.DeleteFile(this, row.Values[HINH_ANH.cl_URL_IMAGE]);

                //  HelpControls.ShowMsgBox(this, "Xóa dữ liệu thành công!");
                InitDataSlide();
                if (delete == keySlide.Value)
                {
                    txtSapXepSlide.Text = "";
                    lblNgayTaoSlide.Text = "";
                    txtURLSlide.Text = "";
                    ddLoaiBVSlide.SelectedValue = "-1";
                    ddlBVSlide.SelectedValue = "-1";
                    ckcHiden.Checked = false;
                    imageSlide.ImageUrl = "";
                    keySlide.Value = "";
                }
            }
            else
            {
                HelpControls.ShowMsgBox(this, "Dữ liệu đang được sử dụng!");
            }

        }

    }
    protected void gridViewSlideShow_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            ((LinkButton)e.Row.Cells[1].Controls[0]).OnClientClick = "return confirm('Bạn có chắc là muốn xóa dữ liệu này?');";
            DataRowView v = e.Row.DataItem as DataRowView;
            ((CheckBox)e.Row.Cells[2].FindControl("ckcGridHiden")).Checked = v["IS_HIDEN"].ToString() == "Y";
        }
    }
    protected void ckcGridHiden_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox c = (CheckBox)sender;
        
        System.Web.UI.WebControls.GridViewRow row = (System.Web.UI.WebControls.GridViewRow)(c.Parent.Parent);
        string id = gridViewSlideShow.DataKeys[row.DataItemIndex].Value.ToString();
        string sql = string.Format(@"update hinh_anh
        set is_hiden='{0}' where id={1}", c.Checked ? "Y" : "N", id);
        bool b = SQLConnectWeb.ExecSQL(sql);
        if (id == keySlide.Value)
            ckcHiden.Checked = c.Checked;
    }
    protected void imgBtnUp_CheckedChanged(object sender, EventArgs e)
    {
        ImageButton c = (ImageButton)sender;
        System.Web.UI.WebControls.GridViewRow row = (System.Web.UI.WebControls.GridViewRow)(c.Parent.Parent);
        if (row.DataItemIndex > 0)
        {
            string preId = gridViewSlideShow.DataKeys[row.DataItemIndex - 1].Value.ToString();
            string id = gridViewSlideShow.DataKeys[row.DataItemIndex].Value.ToString();
            string sql = string.Format(@"UPDATE HINH_ANH
                    SET	SAP_XEP = CASE WHEN id = {0} THEN {1} ELSE {2} END 
                    WHERE id IN ({0},{4})", id, row.DataItemIndex, row.DataItemIndex + 1, id, preId);
            if (SQLConnectWeb.ExecSQL(sql))
                InitDataSlide();
        }
    }
    protected void imgBtnDown_CheckedChanged(object sender, EventArgs e)
    {
        ImageButton c = (ImageButton)sender;
        System.Web.UI.WebControls.GridViewRow row = (System.Web.UI.WebControls.GridViewRow)(c.Parent.Parent);
        if (row.DataItemIndex < gridViewSlideShow.Rows.Count - 1)
        {
            string nextId = gridViewSlideShow.DataKeys[row.DataItemIndex + 1].Value.ToString();
            string id = gridViewSlideShow.DataKeys[row.DataItemIndex].Value.ToString();
            string sql = string.Format(@"UPDATE HINH_ANH
                    SET	SAP_XEP = CASE WHEN id = {0} THEN {1} ELSE {2} END 
                    WHERE id IN ({0},{4})", id, row.DataItemIndex+1, row.DataItemIndex, id, nextId);
            if (SQLConnectWeb.ExecSQL(sql))
                InitDataSlide();
        }
    }
    #endregion





  
}
